import { Context } from 'koa';
import svgCaptcha from 'svg-captcha'
import jwt from 'jsonwebtoken';
const { createUser, getUserInfo, getUserList, getUserListByPageInfo, updateById, deleteById, searchUsers } = require('../service/user.service')
const { getPermissionByRoleId } = require('../service/role.service')
const { userRegisterError } = require('../constants/err.type')

interface pageInfo {
    pageNum?: number,
    pageSize?: number
}

class UserController {
    // 获取验证码接口
    public async getCaptcha(ctx: Context) {
        const cap = svgCaptcha.create({
            size: 4,   //验证码个数
            width: 160,  //宽
            height: 60,  //高
            fontSize: 50,  //验证码字体大小
            ignoreChars: "0oO1ilI",  // 验证码字符中排除 0o1i
            noise: 2,   //干扰线条的数量
            color: true,   //验证码的字符是否有颜色，默认没有，如果设定了背景，则默认有
            background: "#eee",  // 验证码图片背景颜色
        });
        let img = cap.data;//验证码
        // ctx.session.code 验证码文字忽略大小写
        ctx.session.captcha = cap.text.toLowerCase();
        ctx.response.type = "image/svg+xml"; //设置返回的数据格式
        ctx.body = img
    }
    // 添加普通用户接口
    public async addUser(ctx: Context) {
        try {
            // 操作数据库
            const res = await createUser(ctx.request.body)
            ctx.body = {
                code: 200,
                message: '用户注册成功',
                result: {
                    id: res.id,
                    user_name: res.logname
                }
            }
        } catch (err) {
            console.log(err)
            ctx.app.emit('error', userRegisterError, ctx)
        }
    }
    // 登录接口
    public async login(ctx: Context) {
        const { username } = ctx.request.body;
        try {
            // 从返回结果对象中剔除password等属性，将剩下的属性放到res对象
            const { verified, verifier, tokensecretkey, creattime, password, ...res } = await getUserInfo({ username })
            const { list } = await getPermissionByRoleId(res.role)
            const permis = [];
            for(const item of list) {
                permis.push(item.permis_info)
            }
            ctx.body = {
                code: 200,
                message: '用户登录成功',
                result: {
                    token: jwt.sign(res, tokensecretkey, { expiresIn: '1d' }),
                    ...res,
                    permis
                }
            }
        } catch (error) {
            console.error('用户登录失败', error)
        }
    }
    // 获取普通用户列表
    public async getUsers(ctx: Context) {
        try {
            let res: any = null;
            let { pageNum, pageSize }: pageInfo = ctx.query;
            if (pageNum && pageSize) {
                pageNum = Math.max(pageNum * 1, 1);
                pageSize = Math.max(pageSize * 1, 1);
                res = await getUserListByPageInfo(pageNum, pageSize);
            } else {
                res = await getUserList();
            }
            ctx.body = {
                code: 200,
                message: '获取普通用户列表成功',
                result: {
                    ...res
                }
            }
        } catch (error) {
            console.error('获取普通用户列表失败', error)
        }
    }
    // 根据id获取用户
    public async getUserById(ctx: Context) {
        try {
            const id = ctx.params.id
            const { verified, verifier, tokensecretkey, creattime, password, ...res } = await getUserInfo({id})
            ctx.body = {
                code: 200,
                message: '获取用户成功',
                result: res
            }
        } catch (error) {
            console.error('根据id获取普通用户失败', error)
        }
    }
    // 根据id更新用户
    public async updateUser(ctx: Context) {
        try {
            const id = ctx.params.id
            const newUser = ctx.request.body
            const oldUser = await getUserInfo({id})
            if(newUser.role == oldUser.role) delete newUser.role
            if(newUser.status == oldUser.status) delete newUser.status
            const res = await updateById(id, newUser)
            if(res) {
                ctx.body = {
                    code: 200,
                    message: '更新用户成功'
                }
            } else {
                ctx.body = {
                    code: 400,
                    message: '当前用户无法修改或者新旧用户信息一样，请重试'
                }
            }
        } catch (error) {
            console.error('根据id获取普通用户失败', error)
        }
    }
    // 根据id删除用户
    public async deleteUser(ctx: Context) {
        try {
            const id = ctx.params.id
            const res = await deleteById(id)
            if(res) {
                ctx.body = {
                    code: 200,
                    message: '删除用户成功'
                }
            } else {
                ctx.body = {
                    code: 500,
                    message: '删除用户失败'
                }
            }
        } catch (error) {
            console.error('根据id删除普通用户失败', error)
        }
    }
    // 通过用户名获取用户
    public async searchUsersByname(ctx: Context) {
        try {
            const name = ctx.query.name
            const pageNum = ctx.query.pageNum
            const pageSize = ctx.query.pageSize
            const { verified, verifier, tokensecretkey, creattime, password, ...res } = await searchUsers({name, pageNum, pageSize})
            ctx.body = {
                code: 200,
                message: '搜索用户成功',
                result: res
            }
        } catch (error) {
            console.error('根据昵称搜索用户失败', error)
        }
    }
}

module.exports = new UserController();